// components/chat/audio/audio.js
/**
 * 微信小程序的InnerAudioContext API对语音支持不太完善
 * 建议放弃语音聊天功能
 */
let app = getApp();
app.globalData.innerAudioContextList = app.globalData.innerAudioContextList || [];
Component({
	options: {
		multipleSlots: true,
		styleIsolation: 'shared',
	},
	/**
	 * 组件的属性列表
	 */
	properties: {
		role: String,
		headimg: String,
		content: Object,
    time: String,
	},

	/**
	 * 组件的初始数据
	 */
	data: {
		role: '',
		headimg: '',
    time: '',
		sec: 0,
		content: {},
		isPlay: false
	},
	audio_key:0,
	/**
	 * 组件的方法列表
	 */
	methods: {
		playAudio() {
			if (this.data.isPlay) {
				this.setData({
					isPlay: false
				})
				return app.globalData.innerAudioContextList[this.audio_key].pause();
			}
			app.globalData.innerAudioContextList[this.audio_key].play()
		}
	},
	lifetimes: {
		ready() {
      this.data.sec = this.data.content.sec || 0;
			let key = this.audio_key =  app.globalData.innerAudioContextList.length;
			app.globalData.innerAudioContextList[key] = wx.createInnerAudioContext();
			app.globalData.innerAudioContextList[key].src = this.data.content.src;
			let loopGetId = setInterval(() => {
				let duration = app.globalData.innerAudioContextList[key].duration;
				if(this.data.sec == 0 && duration > 0){
					this.setData({
						sec: Math.ceil(duration) 
					})
					clearInterval(loopGetId)
				}
			}, 500);
			app.globalData.innerAudioContextList[key].onPlay(() => {
				console.log("播放中")
				this.setData({
					isPlay: true
				})
				app.globalData.innerAudioContextList.forEach((value, index) =>{
					if(index != key){
					  return	value.pause();
					}				
				})
			})
			app.globalData.innerAudioContextList[key].onPause(() => {
				console.log("已暂停")
				this.setData({
					isPlay: false
				})
			})
			app.globalData.innerAudioContextList[key].offEnded(() => {
				console.log("正常已结束")
				this.setData({
					isPlay: false
				})
			})
			app.globalData.innerAudioContextList[key].onStop(() => {
				console.log("已结束")
				this.setData({
					isPlay: false
				})
			})
			
			
		}
	}
})
